package com.yan.controller;

import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {



    @RequestMapping({"/", "/index"})
    public String toindex(Model model){
        model.addAttribute("msg","shiro hello");
        return "index";

    }

    @RequestMapping( "user/add")
    public String add(Model model){
        return "user/add";

    }

    @RequestMapping( "user/update")
    public String update(Model model){
        return "user/update";

    }


    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前穿过来的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录的数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);


        System.out.println("usernamePasswordToken"+usernamePasswordToken);
        try{
            //验证登录  执行登录方法 无异常就ok
            subject.login(usernamePasswordToken);
            return "index";
        }catch (UnknownAccountException e){//UnknownAccountException 用户名不存在
            model.addAttribute("msg","用户名不存在");
            System.out.println("用户名不存在");
            return "login";
        }catch (IncorrectCredentialsException e){//IncorrectCredentialsException 密码错误
            model.addAttribute("msg","密码错误");
            System.out.println("密码错误");
            return "login";
        }




    }



    @RequestMapping("/noauth")
    @ResponseBody  //转化json的格式 么有这个访问不了页面 具体不知道
    public String UnauthorizedS() {

        return "您现在登录的是未授权的页面";
    }

}
